/* eslint-disable no-lonely-if */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { PrimaryC, PrimaryGhostC, SelectC } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import style from './index.less';
import OrderFrom from '../../../InvestmentManage/finaFlockingNew/orderComps/orderFormC';
import AddNoOrderForm from '../../../InvestmentManage/nonstandardOrder/orderComps/addOrder';
import packUp1 from '../../../../assets/busi/workStation/Nonstandard/open_arrow.png';
import packUp2 from '../../../../assets/busi/workStation/Nonstandard/close_arrow.png';
import { uniqueKey, AutomaticSettlement } from '../../../../utils/commonFunc';
import debounce from 'lodash/debounce';

@Form.create()
@connect(({ loading }) => ({ loading }))
export default class AddTradeC extends PureComponent {
  constructor(props) {
    super(props);
    this.onOk = debounce(this.onOk, 1000);
  }

  state = {
    visible: false, // 交易框打开关闭
    securitiesType: '1', // 交易类型
    uid: '', // 唯一标识
    portfolio: '', // 组合id
    tradingcode: '', // 证券代码
  };

  componentDidMount() {
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }

  // 组合变更
  portfolioOnChange = (e) => {
    // 组合id不同则变更当前页面组合id
    this.setState({
      portfolio: e,
    });
  };

  // 证券代码变更
  tradingcodeOnChange = (e) => {
    if (this.state.tradingcode !== e) {
      // 证券代码不同则变更当前页面证券代码
      this.setState({
        tradingcode: e,
      });
    }
  };

  // 用户点击下达或确定按钮
  onOk = async (fn, type) => {
    // fn:0-理财直融,1-非理财直融
    // type：11-试算，2-簿记
    const { portfolio, tradingcode } = this.state;
    const { dispatch } = this.props;
    let data;

    if (fn == '0') {
      data = this.orderForm.getInfo();
    } else {
      // 非理财直融簿记 单独处理 若后期试算改造完成 则只要调用noOrderForm.onOk即可
      if (Number(type) === 2) {
        this.noOrderForm.onOk();
        return;
      } else {
        data = await this.noOrderForm.orderForm.getInfo();
      }
    }

    // 校验页面数据
    if (!data) return;

    data.uid = this.state.uid;
    if (fn == '0') {
      if (data.priceqj < data.price) {
        message.error('净价价格不能大于全价价格!');
        return;
      }
    }
    this.setState({
      btnLoading: true,
    });

    if (data.direction == 1) {
      let productArg = { nodeId: this.state.portfolio }; // 取当前选择组合id
      let url = 'availableAssetM/getFund';

      // 交易试算模块根据【交易模式】，调用不同接口获取资金：若是指令/簿记模式，则调用新的资金接口，若不是，则调用老的接口
      // 暂时不影响理财直融 后期只需要去掉理财直融的判断即可
      if (Number(type) === 11 && fn == '1') {
        if (this.props.modes === 'COMMAND_MODE' || this.props.modes === 'BOOKKEEPING_MODE') {
          productArg = { portfolioCode: this.state.currentCode }; // 取当前选择组合code
          url = 'availableAssetM/queryAvailable';
        }
      }
      dispatch({
        type: url,
        payload: { ...productArg, hkType: '1' },
        callback: (res) => {
          if (Number(type) === 11 && fn == '1' && res) {
            if (this.props.modes === 'COMMAND_MODE' || this.props.modes === 'BOOKKEEPING_MODE') {
              res = [
                {
                  tzeroAvailableFund: res?.t0Fund,
                },
              ];
            }
          }

          if (res && res.length) {
            const { tzeroAvailableFund } = res[0];
            if (parseFloat(tzeroAvailableFund || 0) < parseFloat(data.parValueTotal)) {
              message.error(fn == '0' ? '全价总额不能大于t+0可用!' : '交易总额不能大于t+0可用!');
              this.setState({
                btnLoading: false,
              });
              return;
            }
            this.confirmOk(data, fn, type);
          } else {
            message.error(fn == '0' ? '全价总额不能大于t+0可用!' : '交易总额不能大于t+0可用!');
            // 查询可用资金失败
            this.setState({
              btnLoading: false,
            });
          }
        },
      });
    }
    if (data.direction == 2) {
      // 交易试算模块根据【交易模式】，调用不同接口获取资金：若是指令/簿记模式，则调用新的资金接口，若不是，则调用老的接口
      // 暂时不影响理财直融 后期只需要去掉理财直融的判断即可
      let portfolioArg = { fundId: this.state.portfolio, tradingcode: tradingcode.tradingCode, exchangecode: tradingcode.exchangeCode };
      let tradeUrl = 'tradeHoldM/getPosition';
      if (Number(type) === 11 && fn == '1') {
        if (this.props.modes === 'COMMAND_MODE' || this.props.modes === 'BOOKKEEPING_MODE') {
          portfolioArg = { portfolioCode: this.state.currentCode, tradingCode: tradingcode.tradingCode, exchangeCode: tradingcode.exchangeCode };
          tradeUrl = 'tradeHoldM/queryAvailablePosition';
        }
      }
      dispatch({
        type: tradeUrl,
        payload: {
          securityType: fn == '0' ? '7' : '12',
          ...portfolioArg,
          hkType: '1',
        },
        callback: (res) => {
          if (res) {
            const { availableAmount } = res;
            if (parseFloat(availableAmount || 0) < parseFloat(data.amount)) {
              message.error(fn == '0' ? '数量不能大于可用数量!' : '交易数量不能大于可用数量!');
              this.setState({
                btnLoading: false,
              });
              return;
            }
            this.confirmOk(data, fn, type);
          } else {
            message.error(fn == '0' ? '数量不能大于可用数量!' : '交易数量不能大于可用数量!');
            this.setState({
              btnLoading: false,
            });
          }
        },
      });
    }
  };

  confirmOk = (params, fn, type) => {
    // 指令下达 簿记保存请求后台
    const { dispatch } = this.props;
    let url = '';
    if (fn == '0') {
      switch (type) {
        // 簿记
        case '2':
          url = 'finaFlockingM/tradeBookSave';
          break;
        // 组合试算
        case '11':
          url = 'portfolioTrialAddM/finaFlockingSave';
          break;
        default:
          url = '';
      }
    } else {
      switch (type) {
        // 簿记
        case '2':
          url = 'nonstandardOrderM/tradeBookSave';
          break;
        // 组合试算
        case '11':
          url = 'portfolioTrialAddM/nonstandardOrderSave';
          break;
        default:
          url = '';
      }
    }
    if (type == '2' || fn == '0') {
      params.method = '0';
      params.tradeInstruction = { direction: params.direction, stockCode: params.tradingcode };
    }

    if (type == '2') {
      // 判断租户是否配置自动交收，若配置自动交收给予弹窗提醒
      if (
        AutomaticSettlement(2, url, params, dispatch, (res) => {
          if (res && res.success) {
            // 簿记下达成功
            this.onCancel(); // 初始化form表单
            message.success('簿记下达成功!');
          } else {
            message.error(res ? res.message : '簿记下达失败!');
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        })
      )
        return;
    }

    dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: (res) => {
        if (res && res.success) {
          if (type == 11) {
            // this.props.tradeTrialRefresh();
          }
          this.onCancel();
          message.success(type == 2 ? '簿记下达成功!' : '组合试算下达成功');
        } else {
          message.error(res ? res.message : type == 2 ? '簿记下达失败!' : '组合试算下达失败');
        }
        if (Number(type) !== 11) {
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        }
      },
    });
  };

  // 关闭交易框
  onCancel = () => {
    this.setState({ visible: false, securitiesType: '1', btnLoading: false });
  };

  render() {
    const { visible, btnLoading } = this.state;
    const { loading, modes } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12, offset: 0 },
        sm: { span: 12, offset: 0 },
        md: { span: 6, offset: 0 },
        lg: { span: 10, offset: 0 },
        xl: { span: 9, offset: 0 },
        xxl: { span: 10, offset: 0 },
      },
      wrapperCol: {
        xs: { span: 12, offset: 0 },
        sm: { span: 12, offset: 0 },
        md: { span: 18, offset: 0 },
        lg: { span: 14, offset: 0 },
        xl: { span: 15, offset: 0 },
        xxl: { span: 14, offset: 0 },
      },
    };
    return (
      <div>
        {visible && (
          <div className={style.openBox}>
            <div className={style.title}>
              <span>交易要素</span>
              <img src={packUp2} onClick={this.onCancel}></img>
            </div>
            <div className={style.content}>
              <SelectC
                form={this.props.form}
                dataIndex='securities'
                title='证券子类'
                dataSource={[
                  { title: '理财直融', value: '0' },
                  { title: '非理财直融', value: '1' },
                ]}
                initialValue={'1'}
                onChange={(e) => {
                  this.setState({ securitiesType: e });
                }}
                formItemLayout={formItemLayout}
                style={{ paddingRight: '20px' }}
              />
              {/* 理财直融 */}
              {this.state.securitiesType == '0' && (
                <OrderFrom
                  type={2}
                  workStation={true}
                  portfolioOnChange={this.portfolioOnChange}
                  tradingcodeOnChange={this.tradingcodeOnChange}
                  portfolioCode={() => {}}
                  productCode={() => {}}
                  wproductid={this.props.rootId}
                  wportfolioid={this.props.portfolioid ? this.props.portfolioid : this.props.rootId}
                  onRef={(ref) => {
                    this.orderForm = ref;
                  }}
                />
              )}
              {/* 非理财直融 */}
              {this.state.securitiesType == '1' && (
                <AddNoOrderForm
                  type={2}
                  workStation={true}
                  portfolioOnChange={this.portfolioOnChange}
                  tradingcodeOnChange={this.tradingcodeOnChange}
                  onChangePortfolioCode={(e) => this.setState({ currentCode: e })}
                  wproductid={this.props.rootId}
                  wportfolioid={this.props.portfolioid ? this.props.portfolioid : this.props.rootId}
                  onRef={(ref) => {
                    this.noOrderForm = ref;
                  }}
                  onCancel={this.onCancel}
                />
              )}
            </div>
            <div className={style.footButton}>
              <PrimaryC title='试算' onClick={() => this.onOk(this.state.securitiesType, '11')} loading={btnLoading} />
              {/* 【交易模式】不为簿记/指令模式，则隐藏“簿记”按钮 */}
              {(modes == 'BOOKKEEPING_MODE' || modes == 'COMMAND_MODE') && (
                <PrimaryGhostC title='簿记' onClick={() => this.onOk(this.state.securitiesType, '2')} loading={btnLoading} />
              )}
              <PrimaryGhostC title='取消' onClick={this.onCancel} />
            </div>
          </div>
        )}
        {!visible && (
          <div
            id='nonstandAddTrade'
            className='normalCloseBox'
            onMouseMove={() => {
              document.getElementById('nonstandAddTrade').className = 'hoverCloseBox';
            }}
            onMouseLeave={() => {
              document.getElementById('nonstandAddTrade').className = 'normalCloseBox';
            }}
            onClick={() => this.setState({ visible: true })}
          >
            <span>添加交易</span>
            <img src={packUp1}></img>
          </div>
        )}
      </div>
    );
  }
}
